﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO.Compression;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace WebApplication1
{
    /// <summary>
    /// Summary description for Handler
    /// </summary>
    public class Handler : IHttpHandler
    {
        sv_QuanLyNhaSach.AdapterClient sv;
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                sv = new sv_QuanLyNhaSach.AdapterClient();
                string ma = context.Request.QueryString["ID"];
                context.Response.ContentType = "image/jpg";
                byte[] hinh= sv.Layhinh(ma);
                context.Response.BinaryWrite((byte[])Decompress(hinh));
            }
            catch (Exception ex)
            {
            }
            finally
            {
                sv.Close();
            }
        }
        public object Decompress(byte[] gzip)
        {
            using (DeflateStream stream = new DeflateStream(new MemoryStream(gzip), CompressionMode.Decompress))
            {
                const int size = 4096;
                byte[] buffer = new byte[size];
                using (MemoryStream memory = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = stream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            memory.Write(buffer, 0, count);
                        }
                    }
                    while (count > 0);
                    var dataOut = memory.ToArray();
                    MemoryStream _MemoryStreamb = new MemoryStream(dataOut);
                    BinaryFormatter _BinaryFormatterb = new BinaryFormatter();
                    // Serializes an object, or graph of connected objects, to the given stream.
                    return _BinaryFormatterb.Deserialize(_MemoryStreamb);
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}